package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ServiceProvider;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.ServiceProviderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ServiceProviderMapper serviceProviderMapper;
    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    public void add(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setProviderId(shoppingCartDTO.getProviderId());
        // 查询服务人员信息
        ServiceProvider provider = serviceProviderMapper.getById(shoppingCartDTO.getProviderId());
        if(provider == null){
            throw new RuntimeException("服务人员不存在");
        }
        shoppingCart.setName(provider.getName());
        shoppingCart.setAmount(provider.getPrice());
        shoppingCart.setImage(provider.getImage());
        // 查询是否已存在
        ShoppingCart query = new ShoppingCart();
        query.setUserId(shoppingCart.getUserId());
        query.setProviderId(shoppingCartDTO.getProviderId());
        List<ShoppingCart> list = shoppingCartMapper.list(query);
        if (list != null && list.size() == 1) {
            ShoppingCart exist = list.get(0);
            exist.setNumber(exist.getNumber() + 1);
            shoppingCartMapper.updateNumberById(exist);
        } else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 查看购物车
     * @return
     */
    public List<ShoppingCart> show() {
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        return shoppingCartList;
    }

    /**
     * 清空购物车
     */
    public void clean() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.cleanByUserId(userId);
    }
}
